<style scoped>
.dialog-footer button:first-child {
  margin-right: 10px;
}

input {
  padding: 0 0 0 1px;
  width: 70%;
  margin-left: 10px;
}

textarea {
  width: 70%;
  height: 70px;
  margin-left: 10px;
  padding: 1px 0 0 2px;
}
</style>

<template>
  <!-- border: 1px solid blue -->
  <div style=" padding: 10px;height: 75vh;width: 100%;box-sizing: border-box">

    <!-- 搜索区域 -->
    <div style="margin: 0 0 10px 1px">
      <el-input @keyup="Load" v-model="data.SearchKeyWord" maxlength="30" placeholder="请输入关键字（仅问题描述、反馈者和联系方式可查）"
                style="width: 30%"
                clearable></el-input>
      <el-button
          type="danger"
          style="margin-left: 10px"
          @click="handleBatchDelete"
          :disabled="data.selectedRows.length === 0">
        批量删除
      </el-button>
    </div>

    <!--  表格  -->
    <!-- header-cell-style设置头部居中；cell-style设置单元格内容居中;stripe斑马纹 -->
    <!--  sortable实现排序按钮  -->
    <el-table
        :data="data.tableData"
        :header-cell-style="{ 'text-align': 'center' }"
        :cell-style="{ 'text-align': 'center' }"
        border
        stripe
        style="width: 98%; border-radius: 5px;margin-left: 1%"
        @selection-change="handleSelectionChange"
    >
      <el-table-column fixed type="selection" sortable prop="feedbackId" width="100" label="问题ID"/>
      <el-table-column sortable prop="feedbackDescription" width="180" label="问题描述">
        <template #default="scope">
          <div style="white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">
            <el-tooltip class="item" effect="dark" :content="scope.row.feedbackDescription" placement="top">
              <span>{{ scope.row.feedbackDescription }}</span>
            </el-tooltip>
          </div>
        </template>
      </el-table-column>
      <el-table-column sortable width="200" label="反馈图片">
        <template #default="scope">
          <img
              v-if="scope.row.feedbackImgUrl"
              :src="scope.row.feedbackImgUrl"
              style="width: 50px; height: 50px; object-fit: cover; border-radius: 5px;cursor: pointer"
              alt="反馈图片"
              @click="viewImage(scope.row.feedbackImgUrl)"
          >
          <el-text v-else>无反馈图片</el-text>
        </template>
      </el-table-column>
      <el-table-column sortable prop="feedbackProviderContact" width="150" label="联系方式"/>
      <el-table-column sortable prop="username" width="150" label="反馈者"/>
      <el-table-column sortable prop="feedbackTime" width="200" label="反馈时间"/>
      <el-table-column sortable width="150" label="处理状态">
        <template #default="scope">
          <el-text v-if="scope.row.status === 1">已处理</el-text>
          <el-text v-else>未处理</el-text>
        </template>
      </el-table-column>

      <el-table-column sortable fixed="right" label="操作" min-width="230">
        <template #default="scope">
          <el-popconfirm title="确定永久删除吗?" @confirm="handleDelete(scope.row.feedbackId)">
            <template #reference>
              <el-button type="primary" link :icon="Delete">删除</el-button>
            </template>
          </el-popconfirm>
          <el-button v-if="scope.row.status === 1" link type="primary"
                     @click="updateToUnprocessed(scope.row.feedbackId)" :icon="Discount">标为未处理
          </el-button>
          <el-button v-else link type="primary" @click="updateToProcessed(scope.row.feedbackId)" :icon="Discount">
            标为已处理
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 图片预览对话框 -->
    <el-dialog
        v-model="data.dialogVisible"
        width="30%"
    >
      <img :src="data.previewImageUrl" alt="预览图片" style="width: 100%;">
    </el-dialog>

    <!--  分页  -->
    <el-pagination
        v-model:current-page="data.currentPage"
        v-model:page-size="data.pageSize"
        :page-sizes="[10, 15, 20]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="data.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="margin-top: 1%"
    ></el-pagination>
  </div>

  <div style="height: 8vh;">

  </div>
</template>

<script setup>
import {reactive} from "vue";
import {Delete, Discount} from '@element-plus/icons-vue'
import request from "../utils/request.js";
import {ElLoading, ElMessage, ElMessageBox} from 'element-plus';

const dataString = localStorage.getItem('data');


const data = reactive({
  //当前页
  currentPage: 1,
  //每页多少条数据
  pageSize: 10,
  //搜索输入框
  SearchKeyWord: "",
  //数据条数
  total: 0,
  //表格数据
  tableData: [],
  selectedRows: [], // 选中行的数组
  dialogVisible: false,
  previewImageUrl: ''
});

const Load = () => {
  let loadingInstance = ElLoading.service({fullscreen: true}); // 启动全屏加载动画
  console.log("搜索框关键词：", data.SearchKeyWord);

  request.get(`/java/problem/feedback/getAll?current=${data.currentPage}&size=${data.pageSize}&SearchKeyWord=${data.SearchKeyWord}`)
      .then((response) => {
        console.log("问题反馈数据：", response);
        data.tableData = response.data.records;
        data.total = response.data.total;
      })
      .catch((error) => {
        console.error('请求发生错误:', error);
      })
      .finally(() => {
        loadingInstance.close();
      });
};

Load()

//改变分页大小
const handleSizeChange = (pageSize) => {
  data.currentPage = 1
  data.pageSize = pageSize
  Load()
}

//去到第几页
const handleCurrentChange = (currentPage) => {
  data.currentPage = currentPage
  Load()
}

//删除
const handleDelete = async (feedbackId) => {
  try {
    const res = await request.delete("/java/problem/feedback/deleteById/" + feedbackId);
    console.log(res);
  } catch (e) {
    console.log(e);
  }

  handleCurrentChange(1);
};


//批量删除
const handleSelectionChange = (selected) => {
  data.selectedRows = selected;
};

const handleBatchDelete = async () => {
  const selectedIds = data.selectedRows.map(row => row.feedbackId);
  if (selectedIds.length === 0) {
    console.warn('没有选中任何行');
    return;
  }
  console.log('选中的行ID：', selectedIds);

  // 确认是否删除
  const confirmDelete = await ElMessageBox.confirm(
      '确定永久删除选中的行吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  );

  if (confirmDelete) {
    // 执行批量删除操作
    try {
      const res = await request.delete('/java/problem/feedback/delete/' + selectedIds);
      console.log('批量删除返回信息：', res);
      // 成功后刷新列表
      Load();
    } catch (error) {
      console.error('批量删除失败：', error);
    }
  }
};

// 点击图片时触发的功能，用于打开对话框并展示图片
const viewImage = (url) => {
  data.previewImageUrl = url;
  data.dialogVisible = true;
};

const updateToUnprocessed = (feedbackId) => {
  const status = 0;
  request.put(`/java/problem/feedback/updateTag/` + feedbackId + `/` + status).then((res) => {
    if (res.code === 200) {
      ElMessage.info(res.data)
      Load()
    } else {
      ElMessage.error(res.data)
    }
  })
}

const updateToProcessed = (feedbackId) => {
  const status = 1;
  request.put(`/java/problem/feedback/updateTag/` + feedbackId + `/` + status).then((res) => {
    if (res.code === 200) {
      ElMessage.info(res.data)
      Load()
    } else {
      ElMessage.error(res.data)
    }
  })
}

</script>
